package cn.dfun.demo.scdemo.ali.sentinel.controller;

import cn.dfun.demo.scdemo.ali.sentinel.handler.CustomBlockHandler;
import cn.dfun.demo.scdemo.common.entity.CommonResult;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RateLimitController {
    /**
     * 根据资源名称限流,另外还可根据url限流
     */
    @GetMapping("/byResource")
    @SentinelResource(value="byResource", blockHandler = "handleException")
    public CommonResult byResource() {
        return CommonResult.success();
    }

    public CommonResult handleException(BlockException exception) {
        log.info(exception.getClass().getCanonicalName() + "服务不可用");
        return CommonResult.fail();
    }

    /**
     * 自定义限流处理类和处理方法
     */
    @GetMapping("/customBlockHandler")
    @SentinelResource(value="byResource",
            blockHandlerClass=CustomBlockHandler.class, // 指定处理类
            blockHandler="handleException") // 指定处理方法
    public CommonResult customBlockHandler() {
        return CommonResult.success();
    }
}
